package com.sqfw.project.utils.smgp;


import com.sqfw.project.wp.domain.TSmsSendLog;
import com.sqfw.project.wp.service.TSMSSendLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SMGPSession  implements  Runnable {

	protected static final SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");

	private static final Logger log = LoggerFactory.getLogger(SMGPSession.class);

	@Autowired
	protected SMGPApi api;

	@Autowired
	protected TSMSSendLogService tsmsSendLogService;

	protected boolean allowSend = true;

	protected Object sendLock = new Object();

	private void checkBind() {

		while (!api.isConnected()) {
			try {
				SMGPLoginRespMessage resp = api.connect();
				if (resp != null && resp.getStatus() == 0) {
					log.info("SMGPSession login success host=" + api.getHost() + ",port=" + api.getPort()
							+ ",clientId=" + api.getClientId());
					synchronized (api) {
						api.notifyAll();
					}
					break;
				} else {
					log.error("SMGPSession login fail, host=" + api.getHost() + ",port=" + api.getPort() + ",clientId="
							+ api.getClientId() + ",result=" + resp.getStatus());
				}
			} catch (IOException e) {
				log.error("SMGPSession login error", e);
			}
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {}
		}
	}

	public void send(SMGPSubmitMessage submit) {
		while (!allowSend) {
			synchronized (sendLock) {
				try {
					sendLock.wait();
				} catch (InterruptedException e) {}
			}
		}

		while (!api.isConnected()) {
			synchronized (api) {
				try {
					api.wait();
				} catch (InterruptedException e) {}
			}
		}
		try {
			api.sendMsg(submit);
			log.info("send msg to gateway success:" + submit);
		} catch (IOException e) {
			api.close();
			log.warn("SMGPSession send msg fail,retry :" + submit, e);
			send(submit);
		}

	}

	public void run() {
		//Thread.currentThread().setName("SMGPSession");
		checkBind();
		ActiveTestThread activeThread = new ActiveTestThread(api);
		activeThread.start();
		while (true) {
			try {
				SMGPBaseMessage baseMsg = api.receiveMsg();
				if (baseMsg == null) {
					log.error("SMGPSession receive msg null");
					api.close();
					checkBind();
					continue;
				}
				if (baseMsg instanceof SMGPActiveTestMessage) {
					SMGPActiveTestRespMessage resp = new SMGPActiveTestRespMessage();
					resp.setSequenceNumber(baseMsg.getSequenceNumber());
					api.sendMsg(resp);
				} else if (baseMsg instanceof SMGPActiveTestRespMessage) {
					// do nothing;
					// log.info("get ActiveTestResp msg from gateway:" + baseMsg);
				} else {
					log.info("get msg from gateway:" + baseMsg);
					if (baseMsg instanceof SMGPDeliverMessage) {
						SMGPDeliverMessage smgpDeliverMessage = (SMGPDeliverMessage) baseMsg;
						if (smgpDeliverMessage.getIsReport() == 0){
							// 记录收到的短信 T_SMS_SEND_LOG
						 recordUpLinkSms(smgpDeliverMessage);
						}
					}
				}
			} catch (Exception e) {
				log.error("SMGPSession receive msg error:" + e.getMessage());
				api.close();
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e1) {}
				checkBind();
			}
		}
	}

	// 记录收到的短信
	private void recordUpLinkSms(SMGPDeliverMessage smgpDeliverMessage) {
		TSmsSendLog tSmsSendLog = new TSmsSendLog();
		tSmsSendLog.setReceivePhone(smgpDeliverMessage.getSrcTermId());
		tSmsSendLog.setSmType("收");
		tSmsSendLog.setStatus("已收到");
		tSmsSendLog.setSendTime(new Date());
		tSmsSendLog.setSmContent(smgpDeliverMessage.getMsgContent()); // 收到的短信内容
		 tsmsSendLogService.addSmsSendLog(tSmsSendLog);
	}

}
